<?php
/*
 *  Update active_loans with delay and penalties acumulated on each active loan.
 *  Note that active_loans only deals with the next expected payment for each active loan,
 *  for loans with more than 1 due payment, only the older due payment values are considered.
 */

require_once 'z.php';

$db = Zend_Db_Table_Abstract::getDefaultAdapter();
$date = date('Y-m-d');

/*
 *  Set the system in 'Maintenance' mode. User login is disable, current sessions are closed.
 */
$cronJobs = new Zend_Db_Table(array('name' => 'cron_jobs', 'primary' => 'Id'));
$cronJobs->insert(array('Date' => $date, 'Time' => date('H:i:s'), 'Mode' => 'Maintenance', 'Script' => 'cron.active_loans'));

$db->query(sprintf("
  update
    active_loans al,
    loans l
  set
    al.CurrentDate = '%s',
    al.CurrentDelay = GREATEST(0,(TO_DAYS('%s')-TO_DAYS(NextPaymentDate))),
    al.CurrentPenalties = IF(al.CurrentDelay <= l.DelayGrace, 0, 
        l.DelayPenaltyFixedCharge+0.01*l.DelayPenaltyRate*GREATEST(0,(TO_DAYS('%s')-TO_DAYS(al.NextPaymentDate)))*al.ExpectedPaymentAmount)
  where
    l.LoanId = al.LoanId",$date,$date,$date));

?>



